package com.smrtcold.dev.init;

import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.google.gson.reflect.TypeToken;
import com.smrtcold.dev.config.MqttBase;
import com.smrtcold.dev.config.SpringBen;
import com.smrtcold.dev.dto.dev.base.*;
import com.smrtcold.dev.dto.dev.task.DevTask;
import com.smrtcold.dev.dto.dev.task.RestTask;
import com.smrtcold.dev.dto.pwc.PWC;
import com.smrtcold.dev.dto.pwc.PWCitem;
import com.smrtcold.dev.service.base.BaseServer;
import com.smrtcold.dev.utils.DataUtil;
import com.smrtcold.dev.utils.PWCUtil;
import com.smrtcold.dev.utils.Utils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.SocketTimeoutException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 西门子PLC 协议
 */
@Log4j2
@Service
@RequiredArgsConstructor
@Order(10)
public class SystemInit {


    //电价设置
    public static PWC PWCCONF;
    //设备连接信息
    private static HashMap<String, XMZDevInfo> devconnect = new HashMap<>();//ConcurrentHashMap
    private static Boolean isConnect = true;// 判断程序链接状态，是离线---->与平台失去联系,默认链接成功
    //缓存最后运行状态

    private static Cache<String, Long> SYSCache = Caffeine.newBuilder()
            .expireAfterWrite(10, TimeUnit.SECONDS)
            .removalListener((k, v, cause) -> {
                if ("MQTT_STATUS" == k) {
                    // changeConnect(true);
                }
            }).build();

    private final Scheduler scheduler;
    private final BaseServer baseServer;
    @Value("${sys.apid}")
    private String apid;
    @Value("${sys.backdir}")
    private String backdir;
    private long mid = 0;
    //初始化信息
    private boolean isConfig = false, inittask = false;
    private Boolean ISRUN = true;// 判断是否启动程序

    public static void changeConnect(boolean connect) {
        if (isConnect != connect) {
            isConnect = connect;
            log.warn("mqtt 状态：{}", isConnect);
//            SystemInit plcmqSender = SpringBen.getBean(SystemInit.class);
//            if (isConnect) {
//                plcmqSender.startTask("devTask");
//            } else {
//                plcmqSender.pauseTask("devTask");
//            }
        }
    }

    public static boolean checkstatus(String... devids) {
        try {
            for (String devid1 : devids) {
                if (!devconnect.containsKey(devid1)) {
                    return false;
                }
                XMZDevInfo xmzDevInfo = devconnect.get(devid1);
                if (null == xmzDevInfo) {
                    return false;
                }
                xmzDevInfo.checkStatus();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static XMZDevInfo get(String devid) {
        return devconnect.get(devid);
    }


    public static void addCache(String k) {
        Long time = SYSCache.getIfPresent(k);
        SYSCache.put(k, System.currentTimeMillis());
        if ("MQTT_STATUS".equals(k)) {
            //  changeConnect(false);
        }
    }

    public static void addMsg(String topic, String data) {
        try {
            MqttBase.DevOperation plcmqSender = SpringBen.getBean(MqttBase.DevOperation.class);
            plcmqSender.push(topic, data);
        } catch (Exception e) {
            log.warn("推送消息失败：{}，内容：{},错误：{}", topic, data, e.getMessage());
        }
    }

    @PostConstruct
    public void init() {
        //如果存在锁就说明系统禁用了
        this.ISRUN = !DataUtil.hasLockFile(backdir, "sys");
        log.info("系统状态：{},apid:{}", this.ISRUN ? "运行" : "停止", this.apid);
    }

    @PreDestroy
    public void close() {
        this.baseServer.push(String.format("/%s/sys/log/%s/0", apid, mid), "现场停止系统");
    }

    /**
     * 定时周期执行
     */
    @Async
    @Scheduled(initialDelay = 10000, fixedDelay = 15000)
    public void init_conf() {
        //检查系统状态--是否停止/是否手动停止--上报状态
        if (this.inittask && this.isConfig) return;
        if (!this.isConfig) {
            log.info("获取系统参数....APID:{}", this.apid);
            this.baseServer.push(String.format("/%s/conf/sys", apid), "PWCCONF,DEVLIST");
        }
        if (this.isConfig && this.ISRUN) {
            if (!this.inittask) {
                log.info("获取系统任务....");
                this.baseServer.push(String.format("/%s/all/task", apid), "all");
                this.baseServer.push(String.format("/%s/status/sys/%s", apid, mid), this.ISRUN ? "1" : "0");
                log.info(" get task......{}", this.apid);
            }
        }
    }

    // 每月1日 0:00:00 执行
    @Scheduled(cron = "0 0 0 1 * ?") // 关键配置
    public void executeOnFirstDayOfMonth() {
        //让系统重新初始化
        this.inittask = this.isConfig = false;
        System.gc();
    }


    public Long getMid() {
        return mid;
    }

    public Boolean getISRUN() {
        return this.ISRUN;
    }


    public boolean runTask(long taskid) throws Exception {
        try {
            JobKey jobKey = this.getTaskJobKey(taskid);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (null == jobDetail) return false;
            scheduler.triggerJob(jobKey);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void setISRUN(boolean _isRun, int opertype) {
        String oper = (0 == opertype ? "现场人员" : "远程");
        log.info("{}：控制{}系统", oper, _isRun ? "运行" : "停止");
        // if (_isRun != this.ISRUN) {
        this.ISRUN = _isRun;
        if (this.ISRUN) {
            DataUtil.deleteLockFile(backdir, "sys");
            this.inittask = this.isConfig = false;
            this.init_conf();
        } else {
            //停止任务就删除任务
            DataUtil.createLockFile(backdir, "sys");
            this.cancelTasksByGroup("devTask", true);

            try {
                Thread.sleep(1000);
                Collection<XMZDevInfo> devInfos = devconnect.values();
                for (XMZDevInfo devInfo : devInfos) {
                    devInfo.dist();
                }
                devconnect.clear();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //}
        this.baseServer.push(String.format("/%s/status/sys/%s", apid, mid), this.ISRUN ? "1" : "0");
        this.baseServer.push(String.format("/%s/sys/log/%s/0", apid, mid), oper + (this.ISRUN ? "启动" : "停止") + "系统");


    }

    private void checkSysStatus() {
        if (!isConnect) {
            Long mqtt_status = SYSCache.getIfPresent("MQTT_STATUS");
            if (null == mqtt_status) {
                boolean push = this.baseServer.push(String.format("/%s/sys/link", apid), "0");
                if (push) {
                    //  changeConnect(true);
                }
            }
        }
    }


    /**
     * 初始化配置
     * 过程复杂，需要测试
     *
     * @param apid
     * @param devid:all 全部更新 /其他指定
     * @param conf
     * @param oper:all  全部更新，del 删除
     *                  HMI/apid/all/conf      HMI/apid/devid/[add,update,delete,stop]
     */
    public void initDevConf(String apid, String devid, String oper, String conf) {
        try {
            if (Utils.isNull(conf) || conf.length() < 10) {
                log.warn("配置为空！!!!！ ");
                return;
            }
            if ("all".equals(devid)) {
                devconnect.clear();
            }
            if (null != conf && conf.length() > 10) {
                List<DevInfo> devInfoList = Utils.GSON.fromJson(conf, new TypeToken<List<DevInfo>>() {
                }.getType());
                for (DevInfo devInfo : devInfoList) {
                    mid = devInfo.getMid();
                    JSONObject jsonObject = JSONObject.parseObject(devInfo.getConfversion());
                    List<FboxConfData> typeToken = new ArrayList<>();
                    if (null != devInfo.getConfmapping() && devInfo.getConfmapping().length() > 30) {
                        typeToken = Utils.GSON.fromJson(devInfo.getConfmapping(), new TypeToken<List<FboxConfData>>() {
                        }.getType());
                    }
                    Integer port = jsonObject.getInteger("port");
                    if (null == port) port = 102;
                    XMZDevInfo xmzDevInfo = new XMZDevInfo(EPlcType.S200_SMART, jsonObject.getString("ip"), port, jsonObject.getIntValue("scantime"), apid, devInfo.getDevid(), typeToken);
                    devconnect.put(devInfo.getDevid(), xmzDevInfo);
//                    推送初始化状态
                    this.baseServer.push(String.format("/%s/%s/status", apid, devid), xmzDevInfo.getStatus() ? "1" : "0");
                }
                this.baseServer.push(String.format("/%s/status/sys/%s", apid, mid), this.ISRUN ? "1" : "0");
                log.info("设备配置完成：.....{}", devconnect.size());
            }
            this.isConfig = true;
            //手动调用刷新
            this.init_conf();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void initSysConf(String conf) {
        JSONObject _jobj = JSONObject.parseObject(conf);
        if (_jobj.containsKey("PWCCONF")) {
            PWCCONF = PWCUtil.getPMconf(_jobj.getString("PWCCONF"));
        }
        if (_jobj.containsKey("DEVLIST")) {
            this.initDevConf(apid, "all", "all", _jobj.getString("DEVLIST"));
        }
    }


    /**
     * 数据备份
     *
     * @param devid
     * @return
     */
    public boolean databack(String devid) {
        try {
            //true 说明已经备份成功
            boolean needDataBack = DataUtil.isHasDataBack(this.backdir, devid);
            if (needDataBack) return true;
            XMZDevInfo xmzDevInfo = devconnect.get(devid);
            List<Point> datas = (List<Point>) xmzDevInfo.readll(true, false);
            if (datas.isEmpty()) return false;
            DataUtil.backupData(backdir, devid, datas);
            log.info("设备：{}:备份数据：{}成功！", devid, datas.size());
            return true;
        } catch (SocketTimeoutException e) {

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


//    private boolean push(String topic, String data) {
//        try {
//            this.devOperation.push(this.topicprefix+topic, data);
//            return true;
//        } catch (Exception e) {
//            log.warn("推送消息失败：{}，内容：{},{}", topic, data, e.getMessage());
//        }
//        return false;
//    }


    /**
     * 初始化定时任务
     *
     * @param apid
     * @param taskid
     * @param --->   HMI/apid/all/task
     *               HMI/apid/[all/id]/[add,update,delete]
     *               HPI/apid/taskid/task/[add,update,delete,run]
     */
    public void initTask(String apid, String taskid, String oper, String task) {
        try {
            //这个是调试时
            if ("all".equals(taskid) || "init".equals(taskid)) {
                cancelTasksByGroup("devTask", false);
            }
            if ("del".equals(oper) || "stop".equals(oper)) {
                JobKey taskJobKey = getTaskJobKey(Long.parseLong(taskid));
                this.resetTask(taskJobKey);
                scheduler.pauseJob(taskJobKey);
                log.info("删除/停止任务：{}-{}-成功！", taskid);
                this.baseServer.push(String.format("/%s/sys/log/%s/0", apid, mid), "停止任务" + taskid);
            }
            if ("run".equals(oper)) {
                JobDetail jobDetail = scheduler.getJobDetail(getTaskJobKey(Long.parseLong(taskid)));
                if (null != jobDetail) {
                    scheduler.triggerJob(getTaskJobKey(Long.parseLong(taskid)));
                    this.baseServer.push(String.format("/%s/sys/log/%s/", apid, mid, 0), "运行任务" + taskid);
                } else {
                    DevTask devTask = Utils.GSON.fromJson(task, DevTask.class);
                    this.mid = devTask.getMid();
                    boolean b = this.runOneTaskJob(devTask);
                    this.baseServer.push(String.format("/%s/sys/log/%s/", apid, mid, devTask.getId()), "任务运行" + (b ? "成功" : "失败"));
                }

            } else {
                //如果系统处于运行状态
                if (this.ISRUN) {
                    if (Utils.isnotNull(task) && task.length() > 20) {
                        List<DevTask> tasks = Utils.GSON.fromJson(task, new TypeToken<List<DevTask>>() {
                        }.getType());
                        int count = 0, run = 0, pause = 0, err = 0;
                        for (DevTask devTask : tasks) {
                            try {
                                if (this.crateTaskJob(devTask)) {
                                    run++;
                                } else {
                                    pause++;
                                }
                                count++;
                            } catch (Exception e) {
                                err++;
                            }
                        }
                        log.info("收到{}个任务：错误{},暂停：{} 运行：{}！", tasks.size(), err, pause, run);
                    }
                } else {
                    log.info("系统停止，任务不创建！");
                    this.baseServer.push(String.format("/%s/status/sys/%s", apid, mid), this.ISRUN ? "1" : "0");
                    //如果系统处于停止状态，置为运行状态，重新初始化程序
                    // this.setIsRun(true,1);
                    //this.init_conf();
                }

            }
            this.inittask = true;
        } catch (Exception e) {
            e.printStackTrace();
            this.baseServer.push(String.format("/%s/sys/log/%s/0", apid, mid), e.getMessage());
        }
    }

    /**
     * 全局停止：这里
     *
     * @param group
     * @param isRunset
     */
    public void cancelTasksByGroup(String group, boolean isRunset) {
        // 获取所有调度任务
        try {
            GroupMatcher<JobKey> matcher = GroupMatcher.groupEquals(group);
            Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
            if (isRunset) {
                log.info("开始回滚任务！！！");
                for (JobKey jobKey : jobKeys) {
                    this.scheduler.pauseJob(jobKey);
                    try {

                        this.resetTask(jobKey);
                    } catch (SchedulerException e) {
                        e.printStackTrace();
                    }
                }
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (JobKey jobKey : jobKeys) {
                try {
                    scheduler.deleteJob(jobKey);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 回滚参数
     *
     * @param jobKey
     * @throws SchedulerException
     */
    private synchronized void resetTask(JobKey jobKey) throws SchedulerException {
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (null != jobDetail) {
            DevTask task = (DevTask) jobDetail.getJobDataMap().get("TASK");
            String resetparam = task.getResetparam();
            if (null != task.getReset() && task.getReset() && Utils.isnotNull(resetparam)) {
                if (null == task.getStatus() || !task.getStatus()) {
                    this.baseServer.push(String.format("/%s/task/log/%s/%s", apid, mid, task.getId()), "任务未激活！不需要回滚");
                    return;
                }
                StringBuffer resmgs = new StringBuffer(task.getName() + " 开始回滚：");
                RestTask re = Utils.GSON.fromJson(resetparam, RestTask.class);
                if (null != re.getSetPoint() && re.getSetPoint().size() > 0) {
                    List<Point> setPoint = re.getSetPoint();
                    for (Point point : setPoint) {
                        try {
                            boolean b = this.sendCtl(point.getDevid(), point.getAddres(), point.getValue());
                            resmgs.append("回滚参数: 设备：" + point.getDevid() + " 地址：" + point.getAddres() + " " + point.getValue() + " " + (b ? "成功" : "失败") + "\n");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (null != re.getRunTask() && re.getRunTask().length > 0) {
                    Long[] runTask = re.getRunTask();
                    for (Long id : runTask) {
                        try {
                            JobKey runjobKey = getTaskJobKey(id);
                            scheduler.triggerJob(runjobKey);
                            resmgs.append("回滚任务：" + id + " 运行成功！\n");
                        } catch (SchedulerException e) {
                            e.printStackTrace();
                            resmgs.append(" 回滚任务：" + id + " 运行失败！\r\n");
                        }
                    }
                }
                this.baseServer.push(String.format("/%s/task/log/%s/%s", apid, mid, task.getId()), resmgs.toString());
            }
        }
    }

    //暂停所有设备任务
    public void pauseTask(String group) {
        try {
//            scheduler.shutdown();
            GroupMatcher<JobKey> matcher = GroupMatcher.groupEquals(group);
            // scheduler.pauseJobs(matcher);
            Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
            for (JobKey jobKey : jobKeys) {
                scheduler.pauseJob(jobKey);
                log.info("暂停任务：{}-{}-成功！", jobKey.getName(), jobKey.getGroup());
            }
            // todo 将权限交给PLC 控制
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    //恢复任务
    public void startTask(String group) {
        // 获取所有调度任务
        try {
            GroupMatcher<JobKey> matcher = GroupMatcher.groupEquals(group);
//            scheduler.resumeJobs(matcher);
            Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
            for (JobKey jobKey : jobKeys) {
                scheduler.resumeJob(jobKey);
                log.info("恢复任务：{}-{}-成功！", jobKey.getName(), jobKey.getGroup());
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    public void DelTask(String group) {
        // 获取所有调度任务
        try {
            GroupMatcher<JobKey> matcher = GroupMatcher.groupEquals(group);
            Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
            for (JobKey jobKey : jobKeys) {
                scheduler.deleteJob(jobKey);
                log.info("删除任务：{}-{}-成功！", jobKey.getName(), jobKey.getGroup());
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    public JobKey getTaskJobKey(Long id) {
        return JobKey.jobKey("TASK_" + id, "devTask");
    }

    private void setCoreTask(DevTask devTask) {
        //启用了电价时段策略==则需要设置时段，风机化可能会使用
        if (null != devTask.getPwcstategy() && true == devTask.getPwcstategy() && null != this.PWCCONF) {
            //0:平，1：谷 2：深谷 3：峰 4 ：尖
            PWCitem pwCitem = null;
            String periodtime = devTask.getPeriodtime();
            if (Utils.isNull(periodtime)) return;
            String[] split1 = periodtime.split(",");
            String sttime = "";//每个开始的时间段
            List<String> runtime = new ArrayList<>();
            for (String str : split1) {
                if ("0".equals(str)) {
                    pwCitem = this.PWCCONF.getPpwc();
                } else if ("1".equals(str)) {
                    pwCitem = this.PWCCONF.getGpwc();
                } else if ("2".equals(str)) {
                    pwCitem = this.PWCCONF.getSgpwc();
                } else if ("3".equals(str)) {
                    pwCitem = this.PWCCONF.getFpwc();
                } else if ("4".equals(str)) {
                    pwCitem = this.PWCCONF.getJpwc();
                }
                if (null != pwCitem && null != pwCitem.getTimeslot() && pwCitem.getTimeslot().length > 0) {
                    String[] times = pwCitem.getTimeslot();
                    for (String time : times) {
                        String[] split = time.replaceAll(":00", "").split("-");
                        sttime += split[0] + ",";
                        runtime.add(time);
                    }
                }
            }
            if (sttime.length() > 0) {
                sttime = sttime.substring(0, sttime.length() - 1);
            }
            devTask.setRuntime(runtime);
            if (0 == devTask.getIstiming()) {
                devTask.setCron("0 0/5 " + sttime + " * * ?");//0 0/5 7,11 * * ?
            }
        }
    }

    /**
     * 运行单次任务，运行删掉
     *
     * @param devTask
     * @return
     */
    private boolean runOneTaskJob(DevTask devTask) {
        JobKey jobKey = JobKey.jobKey("RUNTASK_" + devTask.getId(), "devTask");
        try {
            this.crateTask(devTask, jobKey);
            scheduler.triggerJob(jobKey);
            Thread.sleep(3000);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                scheduler.deleteJob(jobKey);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
        return false;
    }


    private boolean crateTaskJob(DevTask devTask) throws Exception {
        return this.crateTask(devTask, null);
    }

    private boolean crateTask(DevTask devTask, JobKey jobKey) throws Exception {
        this.setCoreTask(devTask);
        if (Utils.isNull(devTask.getCron())) {
            throw new Exception("cron表达式不能为空！");
        }
        if (null == jobKey) {
            jobKey = this.getTaskJobKey(devTask.getId());
        }
        Class jobClass = Class.forName("com.smrtcold.dev.task." + devTask.getAction());
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobKey).build();

        if (!devTask.getStatus()) {
            devTask.setCron("0 0 0 ? 2010");
        }

        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(devTask.getCron());
        cronScheduleBuilder.withMisfireHandlingInstructionIgnoreMisfires();
        TriggerKey tag = TriggerKey.triggerKey(devTask.getId().toString(), "task");
        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(tag)
                .withSchedule(cronScheduleBuilder).build();

        jobDetail.getJobDataMap().put("TASK", devTask);//放入运行参数

        // 判断是否存在
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        scheduler.scheduleJob(jobDetail, trigger);
        if (devTask.getStatus()) {
            log.info("创建任务：{}-{}-{}- 任务：{}-{}-表达式：{}成功！", devTask.getId(), devTask.getName(), devTask.getAction(), jobKey.getName(), jobKey.getGroup(), devTask.getCron());
            return true;
        } else {
            scheduler.pauseJob(jobKey);
            scheduler.scheduleJob(jobDetail, trigger);
            log.info("暂停任务：{}-{}-成功！", devTask.getId(), devTask.getName());
            return false;
        }
    }


    public boolean sendCtl(String devid, String addres, Number value) {
        try {
            XMZDevInfo xmzDevInfo = devconnect.get(devid);
            if (null == xmzDevInfo) throw new RuntimeException("设备不存在");
            xmzDevInfo.writeByAddres(addres, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }


    public void getData(String apid, String devid, String resData, String siff) {
        try {
            XMZDevInfo xmzDevInfo = devconnect.get(devid);
            if (null != xmzDevInfo) {
                if (resData.contains("names")) {
                    JSONObject jsonObject = JSONObject.parseObject(resData);
                    String[] names = jsonObject.getJSONArray("names").stream().toArray(String[]::new);
                    //
                    HashMap<String, Object> datas = new HashMap<>();
                    for (String name : names) {
                        Number number = xmzDevInfo.readName(name);
                        if(null!= number){
                            datas.put(name, number);
                        }
                    }
                    this.baseServer.push(String.format("/%s/%s/%s", apid, devid, siff), Utils.GSON.toJson(datas));
                } else {
                    Object datas = xmzDevInfo.readll(true, true);
                    this.baseServer.push(String.format("/%s/%s/%s", apid, devid, siff), Utils.GSON.toJson(datas));
                }

            }
        } catch (Exception e) {
            log.warn("获取数据失败：{}", e.getMessage());
        } finally {
        }
    }

    public void write(String apid, String devid, String resData, String uuid) {
        JSONObject json = new JSONObject();
        json.put("code", 500);
        try {
            if (Utils.isnotNull(resData)) {
                WritePoint writePoint = JSONObject.parseObject(resData, WritePoint.class);
                Point point = writePoint.getPoint();
                if (null != point && Utils.isnotNull(devid) && Utils.isnotNull(point.getAddres()) && null != point.getValue()) {
                    XMZDevInfo xmzDevInfo = devconnect.get(devid);
                    if (null != xmzDevInfo) {
                        boolean b = xmzDevInfo.writeByAddres(point.getAddres(), point.getValue());
                        HashMap<String, Object> data = new HashMap<>();
                        json.put("code", b ? 200 : 500);
                        data.put("key", point.getName());
                        data.put("value", point.getValue());
                        json.put("data", data);
                        // this.baseServer.push(String.format("/%s/%s/data", apid, devid), Utils.GSON.toJson(data));
                        this.baseServer.push(String.format("/%s/%s/write/%s", apid, devid, uuid), Utils.GSON.toJson(json));

                    }
                }

            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    public void read(String apid, String devid, String resData, String uuid) {
        try {
            Point point = JSONObject.parseObject(resData, Point.class);
            XMZDevInfo xmzDevInfo = devconnect.get(devid);
            String addres = point.getAddres();
            if (null != xmzDevInfo && Utils.isnotNull(addres)) {
                String[] _addres = addres.split(",");
                if (_addres.length > 1) {
                    List list = xmzDevInfo.get(_addres);
                    HashMap<String, Object> data = new HashMap<>();
                    for (int i = 0; i < _addres.length; i++) {
                        data.put(_addres[i], list.get(i));
                    }
                    this.baseServer.push(String.format("/%s/%s/read/%s", apid, devid, uuid), Utils.GSON.toJson(data));
                } else {
                    Number number = xmzDevInfo.readAddres(point.getAddres());
                    point.setValue(number);
                    this.baseServer.push(String.format("/%s/%s/read/%s", apid, devid, uuid), Utils.GSON.toJson(point));
                }
            } else {
                JSONObject data = new JSONObject();
                data.put("code", 500);
                data.put("msg", "设备不存在");
                this.baseServer.push(String.format("/%s/%s/read/%s", apid, devid, uuid), Utils.GSON.toJson(data));
            }
        } catch (Exception e) {
            JSONObject data = new JSONObject();
            data.put("code", 500);
            data.put("msg", "读取异常！");
            this.baseServer.push(String.format("/%s/%s/read/%s", apid, devid, uuid), Utils.GSON.toJson(data));
        }


    }

    public void getDevStatus(String apid, String did, String devStatus) {
        List<Object> result = new ArrayList<>();
        try {
            if ("all".equals(devStatus)) {
                HashMap<String, XMZDevInfo> devconnect1 = devconnect;
                for (String devid : devconnect1.keySet()) {
                    XMZDevInfo xmzDevInfo = devconnect1.get(devid);
                    if (null != xmzDevInfo) {
                        HashMap<String, Object> data = new HashMap<>();
                        data.put("devid", devid);
                        data.put("status", xmzDevInfo.getStatus());
                        result.add(data);
                    }
                }
            } else {
                XMZDevInfo xmzDevInfo = devconnect.get(did);
                if (null != xmzDevInfo) {
                    HashMap<String, Object> data = new HashMap<>();
                    data.put("devid", did);
                    data.put("status", xmzDevInfo.getStatus());
                    result.add(data);
                }
            }
        } catch (Exception e) {
            result.add("错误：" + e.getMessage());
        }
        this.baseServer.push(String.format("/%s/%s/%s", apid, did, devStatus), Utils.GSON.toJson(result));
    }
}
